﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;

namespace Eugenhome.Atrium.LibRu.Web
{
    /// <summary>
    /// 
    /// </summary>
    public class LibRuItem
    {
        /// <summary></summary>
        public bool Valid { get; private set; }

        /// <summary></summary>
        public int ID { get; private set; }

        /// <summary></summary>
        public static int IdCount = 0;

        /// <summary></summary>
        public string Link { get; private set; }

        /// <summary></summary>
        public string Description { get; private set; }

        /// <summary></summary>
        public string Title { get; private set; }

        /// <summary>
        /// 
        /// </summary>
        public LibRuItem() { }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="url"></param>
        /// <param name="rawString"></param>
        public LibRuItem(string url, string rawString)
        {
            Valid = rawString.StartsWith("<DT>");

            if (Valid)
            {
                ID = IdCount++;

                Init(url, rawString);
            }
            else
            {
                Valid=!rawString.IndexOf("</tt>", StringComparison.OrdinalIgnoreCase).Equals(-1);

                if (Valid)
                {
                    rawString = rawString.Split(new string[] { "</tt>" }, StringSplitOptions.None)[1];

                    Init(url, rawString);
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="url"></param>
        /// <param name="rawString"></param>
        private void Init(string url, string rawString)
        {
            int index = rawString.IndexOf("href=", StringComparison.OrdinalIgnoreCase);
            int index2 = rawString.IndexOf(">", index,StringComparison.OrdinalIgnoreCase);
            Link = url + "/" + rawString.Substring(index + 5, index2 - index - 5).Trim('\"');

            index = rawString.IndexOf("<b>", StringComparison.OrdinalIgnoreCase);
            index2 = rawString.IndexOf("</b>", StringComparison.OrdinalIgnoreCase);
            Title = rawString.Substring(index + 3, index2 - index - 3);
        }
    }
}